<template>
  <div class="container">
    <div class="header">
      <h1 class="title">错题本</h1>
      <div class="subject-selector">
        <el-select v-model="selectedSubjectId" placeholder="选择科目" class="subject-dropdown">
          <el-option 
            v-for="subject in subjects" 
            :key="subject.id" 
            :label="subject.name" 
            :value="subject.id" 
          />
        </el-select>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 错题列表 -->
    <div v-else-if="favorites.length" class="question-list">
      <el-card 
        v-for="favorite in favorites" 
        :key="favorite.record_id" 
        shadow="hover" 
        class="question-card"
      >
        <div class="question-header">
          <div class="question-meta">
            <span class="question-id">Question ID: {{ favorite.questionId }}</span>
            <span class="error-tag">错题</span>
          </div>
        </div>
        <div class="question-content">
          <pre class="question-stem">{{ getQuestionStem(favorite.content) }}</pre>
          <!-- 选择题选项 -->
          <el-radio-group v-model="selectedAnswers[favorite.questionId]" disabled>
            <el-radio
              v-for="(option, optionIndex) in parseOptions(favorite.content)"
              :key="optionIndex"
              :value="option.label"
              :label="`${option.label}. ${option.text}`"
              class="option-item"
            >
              {{ option.label }}. {{ option.text }}
            </el-radio>
          </el-radio-group>
          <!-- 答案与解析 -->
          <div class="answer-analysis">
            <div class="answer-box">
              <p><strong>正确答案：</strong> {{ favorite.answer || '无答案' }}</p>
            </div>
            <div class="analysis-box">
              <p><strong>解析：</strong> {{ favorite.analysis || '无解析' }}</p>
            </div>
          </div>
        </div>
        <div class="actions">
          <el-button type="text" @click="deleteFavorite(favorite.recordId)" class="delete-btn">
            <i class="fa-solid fa-trash-can"></i> 取消收藏
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <el-empty v-else description="暂无收藏的题目" class="empty-state">
      <el-button type="primary" @click="$router.push('/personalized-exercises')">去刷题</el-button>
    </el-empty>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, watch } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import useUserInfoStore from '@/stores/userInfo.js';

export default defineComponent({
  name: 'ErrorBook',
  setup() {
    const userInfoStore = useUserInfoStore();
    const favorites = ref([]);
    const loading = ref(false);
    const token = ref(localStorage.getItem('token') || null);
    const selectedAnswers = ref({});
    
    // 科目数据（id 对应 book_id）
    const subjects = ref([
      { id: 1, name: '数据结构' },
      { id: 2, name: '操作系统' },
      { id: 3, name: '计算机网络' },
      { id: 4, name: '计算机组织原理' }
    ]);
    
    // 当前选择的科目ID（默认显示数据结构）
    const selectedSubjectId = ref(1);

    // 提取题干内容
    const getQuestionStem = (content) => {
      if (!content) return '无题干';
      const lines = content.split('\n');
      const optionRegex = /^[A-D]\.\s*(.*)$/;
      const stemLines = lines.filter(line => !optionRegex.test(line.trim()));
      return stemLines.join('\n').trim() || '无题干';
    };

    // 解析选项
    const parseOptions = (content) => {
      const lines = content?.split('\n') || [];
      const optionRegex = /^[A-D]\.\s*(.*)$/;
      const options = [];
      for (const line of lines) {
        const match = line.match(optionRegex);
        if (match) {
          options.push({ label: match[0][0], text: match[1].trim() });
        }
      }
      return options;
    };

    // 按科目获取错题
    const fetchFavoritesBySubject = async (subjectId) => {
      if (!token.value) {
        ElMessage.error('请先登录以查看错题本');
        return;
      }
      loading.value = true;
      try {
        // 获取用户错题本列表（可能不需要过滤bookId，直接获取所有错题本）
        const errorBooksResponse = await axios.get('http://localhost:8080/errorbook/selectByUserId', {
          params: {
            userId: userInfoStore.userId || 1,
          },
          headers: {
            Authorization: `Bearer eyJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjEzODAwMTM4MDAxIiwiaWQiOjEsImlhdCI6MTc0OTkxMzk5OSwiZXhwIjoxNzUwMjU5NTk5fQ.bmvoB0J0jHNaB541HO_r7kRNs179VGknr6ADt9EdMKg`,
          },
        });

        console.log('错题本列表响应:', errorBooksResponse.data);

        // 直接使用用户选择的科目ID获取错题记录
        const recordResponse = await axios.get('http://localhost:8080/errorbook/selectAllRecord', {
          params: {
            bookId: subjectId, // 关键修改：直接使用选择的科目ID
            pageNum: 1,
            pageSize: 10,
          },
          headers: {
            Authorization: `Bearer eyJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjEzODAwMTM4MDAxIiwiaWQiOjEsImlhdCI6MTc0OTkxMzk5OSwiZXhwIjoxNzUwMjU5NTk5fQ.bmvoB0J0jHNaB541HO_r7kRNs179VGknr6ADt9EdMKg`,
          },
        });
        
        if (recordResponse.data.code === 0) {
          favorites.value = recordResponse.data.data?.list || [];
          console.log(`获取科目 ${subjectId} 的错题成功，共 ${favorites.value.length} 条`);
        } else {
          ElMessage.error(recordResponse.data.msg || '获取错题失败，请稍后重试');
        }
      } catch (error) {
        console.error('API错误详情:', {
          message: error.message,
          code: error.code,
          response: error.response ? {
            status: error.response.status,
            data: error.response.data,
            headers: error.response.headers,
          } : null,
        });
        ElMessage.error(error.response?.data?.msg || '无法连接到后端服务，请检查网络或服务状态');
      } finally {
        loading.value = false;
      }
    };

    // 加载错题（默认加载当前选择的科目）
    const fetchFavorites = async () => {
      await fetchFavoritesBySubject(selectedSubjectId.value);
    };

    // 删除错题
    const deleteFavorite = async (recordId) => {
      if (!recordId && recordId !== 0) {
        console.error('无效的recordId:', recordId);
        ElMessage.error('操作失败：无效的错题记录ID');
        return;
      }

      if (!token.value) {
        ElMessage.error('请先登录以取消收藏');
        return;
      }

      try {
        const response = await axios.get('http://localhost:8080/errorbook/deleteRecord', {
          params: { recordId },
          headers: {
            Authorization: `Bearer eyJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjEzODAwMTM4MDAxIiwiaWQiOjEsImlhdCI6MTc0OTkxMzk5OSwiZXhwIjoxNzUwMjU5NTk5fQ.bmvoB0J0jHNaB541HO_r7kRNs179VGknr6ADt9EdMKg`,
          },
        });
        
        if (response.data.code === 0) {
          ElMessage.success('取消收藏成功');
          await fetchFavorites();
        } else {
          ElMessage.error(response.data.msg || '取消收藏失败，请稍后重试');
        }
      } catch (error) {
        console.error('删除错题错误详情:', {
          message: error.message,
          code: error.code,
          response: error.response ? error.response.data : null,
        });
        ElMessage.error(error.response?.data?.msg || '删除失败，请检查网络或服务状态');
      }
    };

    // 监听科目选择变化，重新加载对应科目错题
    watch(selectedSubjectId, (newId) => {
      console.log('科目选择变化:', newId);
      fetchFavorites();
    });

    onMounted(() => {
      console.log('错题本组件挂载，初始化加载科目:', selectedSubjectId.value);
      fetchFavorites();
    });

    return {
      favorites,
      loading,
      token,
      selectedAnswers,
      getQuestionStem,
      parseOptions,
      fetchFavorites,
      deleteFavorite,
      subjects,
      selectedSubjectId,
    };
  },
});
</script>

<style scoped lang="scss">
$primary-color: #409EFF;
$secondary-color: #67C23A;
$accent-color: #E6A23C;
$warning-color: #E6A23C;
$error-color: #F56C6C;
$info-color: #909399;
$bg-color: #F5F7FA;
$card-bg: #FFFFFF;
$text-color: #303133;
$text-secondary: #606266;
$border-color: #DCDFE6;

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: $bg-color;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.title {
  font-size: 32px;
  font-weight: 700;
  color: $text-color;
  text-align: center;
  margin-bottom: 20px;
  background: linear-gradient(to right, $primary-color, $error-color);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.subject-selector {
  flex: 1;
  max-width: 300px;
}

.subject-dropdown {
  width: 100%;
}

.loading-container {
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.question-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.question-card {
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  background-color: $card-bg;
}

.question-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.question-header {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid $border-color;
}

.question-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: $text-secondary;
}

.question-id {
  font-weight: 500;
  color: $text-color;
}

.error-tag {
  background-color: rgba(245, 108, 108, 0.1);
  color: $error-color;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 13px;
}

.question-stem {
  font-size: 18px;
  font-weight: 600;
  color: $text-color;
  margin-bottom: 16px;
  white-space: pre-wrap;
  line-height: 1.6;
  padding: 12px;
  background-color: rgba(245, 247, 250, 0.8);
  border-radius: 8px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.options {
  margin-bottom: 16px;
}

.option-item {
  display: block;
  margin-bottom: 12px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.2s ease;
  background-color: rgba(245, 247, 250, 0.3);
}

.option-item:hover {
  background-color: rgba(245, 247, 250, 0.6);
}

.answer-input {
  width: 100%;
  max-width: 400px;
}

.actions {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.delete-btn {
  color: $error-color;
  font-weight: 500;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  
  i {
    margin-right: 4px;
  }
  
  &:hover {
    color: darken($error-color, 10%);
    transform: scale(1.05);
  }
}

.answer-analysis {
  margin-top: 16px;
  padding: 16px;
  background-color: rgba(245, 247, 250, 0.8);
  border-radius: 8px;
  border-left: 4px solid $error-color;
}

.answer-box, .analysis-box {
  margin-bottom: 12px;
}

.answer-box p {
  font-weight: 500;
  color: $text-color;
}

.analysis-box p {
  color: $text-secondary;
  line-height: 1.6;
}

.empty-state {
  margin-top: 50px;
}

.el-skeleton__item {
  background: linear-gradient(90deg, #f2f3f5 25%, #e6e6e6 37%, #f2f3f5 63%);
  background-size: 400% 100%;
  animation: shimmer 1.5s infinite;
}

@keyframes shimmer {
  0% {
    background-position: 100% 0;
  }
  100% {
    background-position: -100% 0;
  }
}
</style>
